package me.seu.demo.serializable;

import java.io.*;

/**
 * JdkSerializableTest
 *
 *
 * @number 53669
 * @since 2021/3/29 下午3:39
 */
public class JdkSerializableTest {

    /**
     * Student序列化
     */
    public static void serialize() {

        Student student = new Student();
        student.setAge(15);
        student.setName("张三");

        ObjectOutputStream ots = null;
        try {
            //指定java对象Person序列化后的字节流输出的目标流
            ots = new ObjectOutputStream(new FileOutputStream("studentStream.txt"));
            //将Person序列化成的字节流写入到目标输出流（此处为文件输出流）中
            ots.writeObject(student);

            System.out.println("序列化成功！");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ots != null) {
                    ots.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Student序列化字节的反序列化操作
     */
    public static void deSerialize() {
        ObjectInputStream inputStream = null;
        try {
            //指定序列化字节流的来源
            inputStream = new ObjectInputStream(new FileInputStream("studentStream.txt"));
            //将字节流反序列化成Object对象（在这里进行了强转）
            Student student = (Student) inputStream.readObject();
            System.out.println("执行反序列化过程成功：" + student.getName() + "-" + student.getAge() + "岁");
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) throws InterruptedException {
        //1. 先执行序列化方法
        serialize();
        Thread.sleep(1000);
        //2. 后执行反序列化方法
        deSerialize();
    }

}
